package org.linlinjava.litemall.admin.web;

/*import com.qiniu.util.StringUtils;*/
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.linlinjava.litemall.admin.annotation.RequiresPermissionsDesc;
import org.linlinjava.litemall.admin.vo.AddUserParam;
import org.linlinjava.litemall.core.util.IpUtil;
import org.linlinjava.litemall.core.util.JacksonUtil;
import org.linlinjava.litemall.core.util.RegexUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.core.util.bcrypt.BCryptPasswordEncoder;
import org.linlinjava.litemall.core.validator.Order;
import org.linlinjava.litemall.core.validator.Sort;
import org.linlinjava.litemall.db.domain.LitemallAdmin;
import org.linlinjava.litemall.db.domain.LitemallUser;
import org.linlinjava.litemall.db.service.CouponAssignService;
import org.linlinjava.litemall.db.service.LitemallUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;

@RestController
@RequestMapping("/admin/user")
@Validated
public class AdminUserController {
    private final Log logger = LogFactory.getLog(AdminUserController.class);

    @Autowired
    private LitemallUserService userService;
    @Autowired
    private CouponAssignService couponAssignService;

    @RequiresPermissions("admin:user:list")
    @RequiresPermissionsDesc(menu = {"用户管理", "会员管理"}, button = "查询")
    @GetMapping("/list")
    public Object list(String username, String mobile,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @Sort @RequestParam(defaultValue = "add_time") String sort,
                       @Order @RequestParam(defaultValue = "desc") String order) {
        List<LitemallUser> userList = userService.querySelective(username, mobile, page, limit, sort, order);
        return ResponseUtil.okList(userList);
    }

    @RequiresPermissions("admin:user:list")
    @RequiresPermissionsDesc(menu = {"用户管理", "会员管理"}, button = "详情")
    @GetMapping("/detail")
    public Object userDetail(@NotNull Integer id) {
    	LitemallUser user=userService.findById(id);
        return ResponseUtil.ok(user);
    }

    @RequiresPermissions("admin:user:list")
    @RequiresPermissionsDesc(menu = {"用户管理", "会员管理"}, button = "编辑")
    @PostMapping("/update")
    public Object userUpdate(@RequestBody LitemallUser user) {
        return ResponseUtil.ok(userService.updateById(user));
    }

    /**
     *根据id修改消费券(这个接口没用到)
     * @param id
     * @param xiaofeiquan
     * @return
     */
    @PostMapping("/crash/add")
    public Object addxiaofeiquan( @RequestParam(defaultValue = "0") Integer id,
                                  @RequestParam(defaultValue = "0") Integer xiaofeiquan) {

        return ResponseUtil.ok(userService.addCrashByid(id,xiaofeiquan));
    }


    /**
     * 根据用户名和手机号来模糊查询：用户id,用户名，手机号
     * @param query
     * @return
     */
    @GetMapping("/query")
    public Object getUserInfoByQuery(@RequestParam(defaultValue = "null") String query){

        List<LitemallUser> userList = userService.getUserInfoByQuery(query);

        return ResponseUtil.ok(userList);
    }

    /**
     * 根据穿过来的id用户id来判断是否存在
     * @param id
     * @return
     */
    @GetMapping("/getUserById")
    public Object getUserByUserId(@RequestParam(defaultValue = "null") String id){

        Integer converId=null;
        if (id !=null){
             converId = Integer.parseInt(id);
        }

        Integer userId = userService.getUserById(converId);

        return ResponseUtil.ok(userId);
    }


    /**
     * 管理员添加用户
     * @param username
     * @param nickname
     * @param mobile
     * @param recommender
     * @param gender
     * @param userLevel
     * @param status
     * @param request
     * @return
     */
    @RequiresPermissions("admin:user:list")
    @RequiresPermissionsDesc(menu = {"用户管理", "会员管理"}, button = "添加用户")
    @PostMapping("/add")
    public Object useradd(@RequestParam(defaultValue = "0") String username,
                          @RequestParam(defaultValue = "0") String nickname,
                          @RequestParam(defaultValue = "0") String mobile,
                          @RequestParam(defaultValue = "0") String recommender,
                          @RequestParam int gender,
                          @RequestParam int userLevel,
                          @RequestParam int status,
                           HttpServletRequest request) {



        String username1 = username;
        String nickname1 = nickname;
        String password = "123";
        String mobile1 = mobile;
        String recommender1 = recommender;
        int gender1 = gender;
        int userlevel1 = userLevel;
        int status1 = status;





        List<LitemallUser> userList = userService.queryByUsername(username);
        if (userList.size() > 0) {
            return ResponseUtil.fail(704, "用户名已注册");
        }

        userList = userService.queryByMobile(mobile);
        if (userList.size() > 0) {
            return ResponseUtil.fail(705, "手机号已注册");
        }

        if (!RegexUtil.isMobileSimple(mobile)) {
            return ResponseUtil.fail(707, "手机号格式不正确");
        }


        LitemallUser user = null;

        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encodedPassword = encoder.encode(password);

        user = new LitemallUser();
        user.setUsername(username1);
        user.setPassword(encodedPassword);
        user.setMobile(mobile1);
        user.setWeixinOpenid(null);
        user.setAvatar("https://yanxuan.nosdn.127.net/80841d741d7fa3073e0ae27bf487339f.jpg?imageView&quality=90&thumbnail=64x64");
        user.setNickname(nickname1);

        user.setGender((byte) gender1);
        user.setUserLevel((byte) userlevel1);
        user.setStatus((byte) status1);

        user.setLastLoginTime(LocalDateTime.now());
        user.setLastLoginIp(IpUtil.getIpAddr(request));
        user.setFSP(0);
        user.setFSPT(0);
        user.setSUN(0);
        user.setSUND(0);
        user.setJianglijin(0);
        user.setXiaofeiquan(0);

        //给用户设置默认商户等级
        user.setSeller(0);
        //给用户设置默认服务中心
        user.setServeCenter(0);

        userService.add(user);



        // 给新用户发送注册优惠券
        couponAssignService.assignForRegister(user.getId());


        //定义一个user对象用来更新用户的直接推荐人和间接推荐人
        //  LitemallUser updateInvitee = new LitemallUser();
       // updateInvitee.setId(user.getId());


        /*************  完成注册 ，添加 用户链信息  ******************************************************************************************/
        //一、是否存在邀请人
        LitemallUser yqm=new LitemallUser();
        String  myuserlian="";

        if (recommender==null && "".equals(recommender)) {
            myuserlian ="";

        }else
        {
            //1.存在邀请人，
            LitemallUser userlian =  userService.GetByUsermobile(recommender);
            //是否存在真实 链
            if(userlian!=null){
                myuserlian += userlian.getUserlian();

                //把邀请人设置为直接邀请人
                yqm.setDirectInvitee(userlian.getId());

                //同时还要根据邀请人查出当前注册用户的间接邀请人
                String[] arry = myuserlian.split(",");
                if (arry.length > 1) {
                    String indirectInvitee = arry[arry.length-2];
                    //从userlian中截取出间接邀请人的id
                    Integer indirectInvitee1 = Integer.parseInt(indirectInvitee);

                    //将截取到的id设置为当前注册用户的简介邀请人
                    yqm.setIndirectInvitee(indirectInvitee1);
                }

            }

        }



        if ("".equals(myuserlian)){
            myuserlian+=user.getId();
        }else {
            myuserlian+= ","+user.getId();
        }

        yqm.setId(user.getId());
        yqm.setUserlian(myuserlian);

        //根据id来更新用户的userlian还有直推人和间推人
        userService.updateById(yqm);
        /*************************************************************************************************/

        return ResponseUtil.ok();
    }


    @PostMapping("/updateFund")
    public Object updateFund(@RequestParam int id,
                             @RequestParam String type,
                             @RequestParam Double money,
                             @RequestParam int compute,
                             @RequestParam String remarks) {

        //获取当前登录的管理员信息
        Subject currentUser = SecurityUtils.getSubject();
        LitemallAdmin admin = (LitemallAdmin) currentUser.getPrincipal();

        System.out.println(admin.getId());
        System.out.println(admin.getUsername());

        int result =  userService.updateFund(id,type,money,compute,remarks,admin.getUsername());

        //litemallMoneyLogService.insertMoney(pay,income,remarks,userId,type);

        return  result>0? ResponseUtil.ok():ResponseUtil.fail();
    }

    /**
     * 设置用户代理等级(暂时不用)
     * 0，就没代理
     * 1，省代
     * 2，市代
     * 3，县代
     * @param userId
     * @param level
     * @return
     */
    @GetMapping("/updateServeCenter")
    public Object updateUserServeCenter(@RequestParam int userId,
                             @RequestParam int level) {

        LitemallUser updateUser = new LitemallUser();
        updateUser.setId(userId);
        updateUser.setServeCenter(level);
        userService.updateById(updateUser);
        return  ResponseUtil.ok();
    }




}
